package com.sishu.njrtsdms.converter;

import org.jetbrains.annotations.NotNull;
import org.jooq.types.UInteger;
import org.jooq.types.ULong;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.NumberUtils;

import cn.hutool.core.util.StrUtil;

public class MyStringToJOOQNumberConverterFactory implements ConverterFactory<String, Number> {
    @Override
    public <T extends Number> @NotNull Converter<String, T> getConverter(@NotNull Class<T> targetType) {
        return new StringToJOOQNumber<>(targetType);
    }


    private record StringToJOOQNumber<T extends Number>(Class<T> targetType) implements Converter<String, T> {

        @Override
        @Nullable
        @SuppressWarnings("unchecked")
        public T convert(String source) {
            if (source.isEmpty()) {
                return null;
            }
            String trimmedStr = StrUtil.trim(source);
            if (ULong.class == this.targetType) {
                return (T) ULong.valueOf(trimmedStr);
            } else if (UInteger.class == this.targetType) {
                return (T) UInteger.valueOf(trimmedStr);
            }

            return NumberUtils.parseNumber(trimmedStr, this.targetType);
        }
    }
}
